package Pages;

import java.io.IOException;
import java.io.InputStream;
import java.util.Random;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.Sprite;

import Const.GConfig;
import Const.IDTouch;
import Core.Event;
import Core.GLives;
import Core.GMain;
import Core.KEY;
import Core.SMSSender;
import Core.Slide;
import Core.TextInput;
import Core.Touch;
import Core.VirtualKEY;
import Pages.sub.Crypto.Crypto;

public class EndGame extends Slide {
	//[COMMANDCODE] [MÃ GAME] [(số random:<15)|(username:<30)|(score)]
	
	// win-lose
	private Image imgSave = null;
	private Image imgBack = null;
	private Image imgStatus = null;
	private Image imgTB = null, imgRuong = null;
	private Image imgBg = null, imgNap = null;
	
	private int h = 0;
	private int score, scoreT = 0;
	private int count = 100;
	private int state = 0;
	private String strWarning = "";
	private TextInput name;
	private VirtualKEY vk;
	
	public static String cuphap, dauso;
	private Random r = null;
	Event eMain = null, ekbSave = null, ekbBack = null;
	
	public void setContent(int iWin, int score){
		this.score = score;
		if(iWin==0 && score==0) count = 30;
		else count = 100;
		try {
			if(iWin == 0) imgStatus = Image.createImage("/lose.png");
			else imgStatus = Image.createImage("/win.png");
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void init(){
		r = new Random();
		
//Del:		getInfoSMS();
		
		try {
			imgBg = Image.createImage("/bg.png");
			imgNap = Image.createImage("/naphom.png");
			imgSave = Image.createImage("/IGP/save.png");
			imgBack = Image.createImage("/IGP/turn.png");
			imgTB = Image.createImage("/textbox.png");
			imgRuong = Image.createImage("/ruong.png");
			
			vk = new VirtualKEY();
			vk.showKeyboard(-1, -1, true);
			name = new TextInput("", 25, TextInput.INPUT_TYPE_ANY);
			GLives.ins.startTextInput();
			vk.setCommand(imgSave, null, imgBack);
			vk.setCommand(ekbSave = new Event(){
				public void action(){
					System.out.println("Save");
					doSaveScore();
				}
			}, ekbBack = new Event(){
				public void action(){
					System.out.println("Back");
					changeState(State.MAIN_MENU);
				}
			});
			
			setContent(1,6000);
//Debug:			GLives.isTouchable = false;
			
			onResize();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void onResize() {
		vk.setBound(-1, -1, -1, GLives.ScreenHeight < 360 ? 185 : 252, GLives.ScreenWidth <= 360 ? (byte)2 : (byte)0);
		int yy = inY + (!GLives.isTouchable ? inH - 70 : (GLives.isTouchable && GLives.ScreenHeight < 300 ? 30 : 90));
		if(vk.isShow() && yy + 26 > GLives.ScreenHeight - vk.getHeight())
			yy = GLives.ScreenHeight - vk.getHeight() - 26;
		name.setBound(inX + inW - 160, yy, 150, 25, 0xFFEEFF);
		name.setFocus();
	}
	
	public void destroy() {
		imgSave = null;
		imgBack = null;
		imgStatus = null;
		imgTB = null;
		imgBg = null;
		imgNap = null;
		imgRuong = null;
	}
	
	public void registerTouch() {
		Touch.addTouchArea(IDTouch.LUU_DIEM, 0, GLives.ScreenHeight - 40, 70, 40);
		Touch.addTouchArea(IDTouch.HOME, GLives.ScreenWidth-70, GLives.ScreenHeight - 40, 70, 40);
	}
	
	public void Click(int ID, int x, int y) {
		switch(ID){
		case IDTouch.LUU_DIEM:
			System.out.println("Click SendSMS");
			if(state == 1) SendSMS();
			break;
		case IDTouch.HOME:
			if(state >= 1) changeState(State.MAIN_MENU);
			break;
		}
	}
	
	public void onkeyDown(int keyCode) {
		if(state == 0 && score != 0){
			name.updateKeyPressed(keyCode);
			name.isFocused = true;
		}
		if(state == 0){
			if(keyCode == KEY.LEFT_SOFTKEY)
				changeState(State.MAIN_MENU);
			else if (keyCode == KEY.OK){
				doSaveScore();
			}
		} else {
			if(keyCode == KEY.LEFT_SOFTKEY && state == 1)
				SendSMS();
			else if(keyCode == KEY.RIGHT_SOFTKEY)
				changeState(State.MAIN_MENU);
		}
	}
	
	private void doSaveScore(){
		if(score == 0) return;
		name.setText(name.getText().trim());
		if(name.getText().length() == 0){
			count = 100;
			return;
		}
		Game game = (Game)GLives.ins.prevSlide;
		if(game.money > 0) game.updateTopScore(game.money, name.getText());
		System.out.println("------- 1 Chuyen Luu diem Server");
		game.saveScore();
		System.out.println("------- 2 Chuyen Luu diem Server");
		state = 1;
		vk.hideKeyboard();
	}
	
	public void touchDown(int ID, int x, int y) {
		if(GLives.isTouchable && score != 0 && vk.isShow()) vk.pointer(x, y);
	}
	public void touchUp(int ID, int x, int y) {
		if(GLives.isTouchable && score != 0 && vk.isShow()){
			vk.pointer_Released(x, y);
			name.updateTouch(x, y);
		}
	}
	
	public void update(){
		if(h < 111){
			h += (111 - h + 4) >> 2;
		}
		
		if(scoreT < score){
			scoreT += 200;
			if(scoreT > score)
				scoreT = score;
		}
		
		if(count > 0){
			count--;
		} else {
			if(score==0) changeState(State.MAIN_MENU);
			if(state == 2) changeState(State.MAIN_MENU);
			if(score != 0) name.update();
		}
	}
	
	public void paint(Graphics g){
		g.setColor(0);
		g.fillRect(0, 0, GLives.ScreenWidth, GLives.ScreenHeight);
		
		g.drawRegion(imgBg, 0, 111 - h, imgBg.getWidth(), h<<1, 0, GLives.ScreenWidth >> 1, GLives.ScreenHeight >> 1, Graphics.HCENTER | Graphics.VCENTER);
		
		g.drawImage(imgStatus, inX + inW - 10, inY + 40, Graphics.RIGHT|Graphics.TOP);
		
		g.drawImage(imgNap, GLives.ScreenWidth>>1, (GLives.ScreenHeight>>1)-h, Graphics.HCENTER|Graphics.BOTTOM);
		g.drawRegion(imgNap, 0, 0, imgNap.getWidth(), imgNap.getHeight(), Sprite.TRANS_MIRROR_ROT180, GLives.ScreenWidth>>1, (GLives.ScreenHeight>>1) + h, Graphics.HCENTER|Graphics.TOP);
		
		if(score != 0 && state == 0) {
			//drawString(g, "Tên bạn: ", name.x, name.y + name.height/2 - 7, 1, 0x999999);
			
			g.drawImage(imgTB, name.x + 2, name.y, 0);
			g.drawImage(imgRuong, name.x + 6, name.y - 8, Graphics.RIGHT|Graphics.TOP);
			name.paint(g);
			
			if (name.getText().length() == 0 && count % 10 > 2)
				drawString(g, "hãy nhập tên bạn...", name.x + 10, name.y + name.height/2 - 7, 0, 0xFFFFFF);
			
			if(!GLives.isTouchable){
				if(state == 0){
					drawStringBold(g, "Lưu điểm", GLives.ScreenWidth>>1, GLives.ScreenHeight - 15, 2, 0x5f3232);
					drawStringBold(g, "Xóa", GLives.ScreenWidth - 5, GLives.ScreenHeight - 15, 1, 0x5f3232);
				}
			}
			
			if(GLives.isTouchable)
				vk.paint(g);
		}
		
		if(state == 2 && count % 10 > 2){
			drawString(g, strWarning, GLives.ScreenWidth>>1, name.y, 2, 0xFF1100);
		}
		
		if(state == 1){
			drawStringBold(g, "Về Menu", GLives.ScreenWidth - 5, GLives.ScreenHeight - 15, 1, 0x5f3232);
			drawStringBold(g, "Gửi", 5, GLives.ScreenHeight - 15, 0, 0x5f3232);

			drawString(g, "Lưu điểm lên server?", inX + 5, inY + 3, 0, 0x999999);
			drawString(g, "Lưu điểm lên server?", inX + 6, inY + 3, 0, 0xFFAA00);
		} else {
			if(!GLives.isTouchable){
				drawStringBold(g, "Về Menu", 5, GLives.ScreenHeight - 15, 0, 0x5f3232);
			}
		}
		
		drawStringBold(g, "bạn có $" + scoreT, inX + inW - 5, inY + 5, 1, 0x0);
	}
	
	private void show(String str){
		strWarning = str;
		count = 50;
		state = 2;
	}
	
//	private void getInfoSMS(){
//		try {
//			String str = "";
//			InputStream is = GMain.gMidlet.getClass().getResourceAsStream("/code.dat");
//			while(true){
//				int c = is.read();
//				if(c == -1)
//					break;
//				else if (c != '\n' && c != '\r' && c != '\t')
//					str += (char)c;
//			}
//			is.close();
//			str = str.trim();
//			int dot = str.indexOf('#');
//			if(dot > 0 && dot < str.length() - 1){
//				cuphap = str.substring(0, dot).trim();
//				dauso = str.substring(dot + 1).trim();
//			} else {
//				cuphap = dauso = "";
//			}
//			
//			System.out.println("--- Cu Phap:=<"+cuphap+"> Dau So:=<" + dauso +">");
//		} catch (IOException e) {
//			cuphap = "UN";
//			e.printStackTrace();
//		}
//	}
	
	private String makeKey(String name, int score){
		String strFake = ("" + r.nextDouble()).substring(0, 12);
		String quote = strFake + "|" + name + "|" + score;
		/* Create a cipher using the first 16 bytes of the passphrase */
		Crypto tea = new Crypto(GConfig.KeyGame.getBytes());
		byte[] original = quote.getBytes();
		byte[] crypt = tea.encrypt(original);
		/* Ensure that all went well */
        String res = new String(crypt);
        return res;
	}
	
	private void SendSMS(){
		if(dauso.length() == 0){
			show("+ Lưu điểm không thành công!");
			return;
		}
		String strMahoa = makeKey(name.getText(), score);
		
		System.out.println("CUPHAP="+(cuphap + " " + GConfig.MaGame + " " + strMahoa));
		System.out.println("LEN="+(cuphap + " " + GConfig.MaGame + " " + strMahoa).length());
		
		SMSSender.sendSMSToConfirmReward(cuphap + " " + GConfig.MaGame + " " + strMahoa, dauso , 
				new Event(){
					public void action() {
						show("Bạn đã lưu điểm lên server thành công!");
					}
				},
				new Event(){
					public void action() {
						show("Lưu điểm không thành công!");
					}
				});
	}
}
